package com.mysiteforme.admin.controller.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import com.mysiteforme.admin.entity.user.ChClass;
import com.mysiteforme.admin.entity.user.ChUser;
import com.mysiteforme.admin.realm.AuthRealm;
import com.mysiteforme.admin.service.system.UserService;
import com.mysiteforme.admin.service.user.ChClassService;
import com.mysiteforme.admin.service.user.ChUserService;
import com.mysiteforme.admin.util.IdWorker;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.RestResponse;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *   前端控制器
 * </p>
 *
 * @author yj
 * @since 2019-04-15
 */
@Controller
@RequestMapping("/class")
public class ChClassController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChClassController.class);

    @Autowired
    private ChClassService chClassService;

    @Resource
    private UserService userService;

    @Resource
    private ChUserService chUserService;

    @GetMapping("list")
    @SysLog("跳转列表")
    public String list(){
        return "/ytzluser/chClass/list";
    }

    @PostMapping("list")
    @ResponseBody
    @SysLog("请求列表数据")
    public LayerData<ChClass> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                      @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                      ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "");
        LayerData<ChClass> layerData = new LayerData<>();
        EntityWrapper<ChClass> wrapper = new EntityWrapper<>();
        wrapper.isWhere(true);
        //拼接sql
        if(map.get("searchInfo")!="" && map.get("searchInfo")!=null){
            String searchInfo = (String)map.get("searchInfo");
            wrapper.like("c.class_name","%"+searchInfo+"%");
        }
        if(map.get("schoolId")!=""&& map.get("schoolId")!=null){
            String schoolId = (String)map.get("schoolId");
            wrapper.andNew().eq("d.school_id",schoolId);
        }
        if(map.get("departmentId")!="" && map.get("departmentId")!=null){
            String departmentId = (String)map.get("departmentId");
            wrapper.andNew().eq("c.department_id",departmentId);
        }
        Page<ChClass> pageData = chClassService.selectByEntityWrapper(new Page<>(page,limit),wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }



    @PostMapping("getClassName")
    @SysLog("查找班级名称")
    @ResponseBody
    public List<ChClass> listData(ServletRequest request){
        Map map=WebUtils.getParametersStartingWith(request,"");
        EntityWrapper<ChClass> wrapper=new EntityWrapper<>();
        if(map.get("departmentId")!=null && map.get("departmentId")!=""){
            wrapper.eq("department_id",(String)map.get("departmentId"));
        }
        if(map.get("classId")!=null && map.get("classId")!=""){
            wrapper.eq("id",(String)map.get("classId"));
        }
        return chClassService.selectList(wrapper);


    }

    @GetMapping("add")
    @SysLog("跳转新增页面")
    public String add(){
        return "/ytzluser/chClass/add";
    }


    @PostMapping("add")
    @SysLog("保存新增数据")
    @ResponseBody
    public RestResponse add(ChClass chClass){
        chClass.setId(IdWorker.getId());
        chClass.setCreationDate(new Date());
        chClass.setCreationBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        chClassService.addInfo(chClass);
        return RestResponse.success();
    }


    @GetMapping("edit")
    @SysLog("跳转编辑页面")
    public String edit(String id, Model model){
        ChClass chClass = chClassService.findById(id);
         model.addAttribute("chClass", chClass);
        return "/ytzluser/chClass/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑数据")
    public RestResponse edit(ChClass chClass){
        if(null == chClass.getId() || ""== chClass.getId()){
            return RestResponse.failure("ID不能为空");
        }
        chClass.setModifyedDate(new Date());
        chClass.setModifyedBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        chClassService.editById(chClass);
        return RestResponse.success();
    }


    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除数据")
    public RestResponse delete(@RequestParam(value = "id",required = false)String id){
        if(null == id || "" == id){
            return RestResponse.failure("ID不能为空");
        }
        EntityWrapper<ChUser> wrapper=new EntityWrapper<>();
        wrapper.isWhere(true);
        wrapper.eq("c.id",id);
        List<ChUser> chUserList = chUserService.findByLinkId(wrapper);
        if(chUserList.size()!=0) return RestResponse.failure("该班级拥有相关学生信息，不能删除");
        boolean res = chClassService.cutById(id);
        if (res)return RestResponse.success();
        else return RestResponse.failure("系统繁忙，请稍后再试");
    }

}